<template>
  <div class="menu_checks_box" :class="{'shrink': isShrink}">
    <!-- <template v-if="menuData && menuData.length"> -->
    <dl class="check_dl" v-if="!isLoading">
      <dt>{{ title ? title : "商品类目" }}</dt>
      <dd>
        <template v-for="item in menuData">
          <div
            class="check_item"
            :key="'menuChecks' + item.id"
            :class="{ active: item.isChecked }"
            @click="clickMenuFn(item)"
          >
            <el-popover
              placement="bottom-start"
              :close-delay="100"
              trigger="hover"
              :disabled="item.id == '0' || !showChild"
              :popper-options="{
                removeOnDestroy: true
              }"
              @show="popoverShow(item.id)"
              :ref="'menuPopover' + item.id"
              :popper-class="'mypopover'"
            >
              <i slot="reference">{{ item.categoryName }}</i>
              <!-- <el-button slot="reference">click 激活</el-button> -->
              <el-cascader-panel
                :options="item.sublist"
                :props="optionProps"
                v-model="checkedDatas"
                @expand-change="elPanelFn(item.id)"
                @change="checkedChangeFn(item)"
              ></el-cascader-panel>
            </el-popover>
          </div>
        </template>
        <i class="shrinkBtn" v-if="shrink" @click="shrinkFn">{{isShrink ? '展开' : '收起'}}</i>
      </dd>
    </dl>
    <!-- loading骨架 -->
    <dl class="skeleton_box" v-else>
      <dt>{{ title ? title : "商品类目" }}</dt>
      <dd><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></dd>
    </dl>
    <!-- <i class="shrinkBtn">展开</i> -->
  </div>
</template>

<script>
export default {
  name: "category_goods",
  // props: ["checkedDatasParent", "title","showChild"],
  props: {
    checkedDatasParent: Object, //绑定的对象
    title: String, //名称
    showChild: {
      //  是否展示二三级分类
      type: Boolean,
      default: true
    },
    shrink:{  //  是否收缩
      type:Boolean,
      default:false
    }
  },
  data() {
    return {
      optionProps: {
        //多选对应字段配置
        value: "id",
        label: "categoryName",
        children: "sublist",
        multiple: true,
        expandTrigger: "hover"
      },
      menuData: [], //分类数据
      countMenuProject: null, //选中的菜单实例
      pId: "0", //父级分类id
      checkedDatas: [], //选中的二级分类集合
      checkedObj: null, //点击以及分类选中的当前对象
      isLoading:true,
      startDatas:null,
      isShrink:true,
    };
  },
  model: {
    prop: "checkedDatasParent",
    event: "returnBack"
  },
  created() {
     this.isShrink = this.shrink;
    this.initDataList(); //初始化选中项
  },
  methods: {
    shrinkFn(){
      this.isShrink = !this.isShrink;
    },
    getProCategoriesNew() {
      this.$axios({
          method: 'get',
          url: '/api/product/GetProCategoriesNew'
        }).then(response => {
          if (response.data.code == 0) {
            let dataList = response.data.data;
            this.startDatas = dataList;
            this.menuData = this.initChecked(dataList);

            this.$store.commit('changeGoodsKindArrNew', { //存入vuex
              arr: dataList
            });
            this.isLoading = false;
            // let goodsKindArrList = [];
            // goodsKindArrList.push(
            //   response.data.data.map((item, index) => {
            //     return item.categoryName;
            //   })
            // );
            // goodsKindArrList.push(
            //   response.data.data.map((item, index) => {
            //     return item.id;
            //   })
            // );
            // this.$store.commit('changegoodsKindArrList', {
            //   arr: goodsKindArrList
            // });
          }
        }).catch(error => {
          console.log(error);
        });
    },
    initDataList() {
      //初始化选中项
      let mData = this.$store.state.goodsKindArrNew;
      if (mData.length) {
        this.menuData = this.initChecked(mData);
        this.$forceUpdate(); //强刷视图
        this.isLoading = false;
      }else{
        this.getProCategoriesNew();
      }
    },
    initChecked(arrPms) {
      //初始化筛选函数，需要单独再赋值 this.menuData = this.initChecked(mData);
      let arr = arrPms ? arrPms : this.menuData;
      for (let i = 0; i < arr.length; i++) {
        let item = arr[i];
        item.isChecked = !i;
        // initData(item);
      }
      return arr;
    },
    checkedChangeFn(itemObj) {
      //下拉菜单选中事件
      this.pId = itemObj.id;
      let data = this.checkedDatas;

      if (data.length) {
        this.menuData.forEach((item, idx) => {
          //只能选中一个一级分类
          item.isChecked = this.pId == item.id;
        });
      }
      let childNames = this.getChildNames(itemObj);
      this.$emit("returnBack", {
        childIds: this.checkedDatas,  //选中的子分类id集合
        childNames: childNames, //选中的子分类名称集合
        parentId: this.pId, //选中的一级分类id
        parentName: itemObj.categoryName  //选中的一级分类名称
      });
      this.$forceUpdate(); //强刷视图
    },
    getChildNames(itemObj){  //获取所有选中的二级分类名称
      let childNames = [];

      if (this.checkedDatas.length && itemObj.sublist) {
        for (let i = 0; i < this.checkedDatas.length; i++) {
          let checkedItemId = this.checkedDatas[i][1];
          getName(itemObj.sublist, checkedItemId);
        }
      }

      function getName(list, checkedItemId) {
        //递归获取当前分类下 选中的 三级分类中文名称
        for (let i = 0; i < list.length; i++) {
          if (checkedItemId == list[i].id) {
            childNames.push(list[i].categoryName);
          }
          if (list[i].sublist) {
            getName(list[i].sublist, checkedItemId);
          }
        }
      }
      return childNames;
    },
    popoverShow(idNum) {
      //获取当前菜单的实例
      this.countMenuProject = this.$refs["menuPopover" + idNum][0];
    },
    elPanelFn(pId) {
      //重新计算popover的位置，防止菜单展开后显示不全
      this.pId = pId;
      this.$nextTick(() => {
        this.countMenuProject.updatePopper();
      });
    },
    clickMenuFn(item) {
      //点击一级菜单按钮
      if (this.checkedObj == item) return;
      this.checkedObj = item;

      if (this.pId != item.id) {
        this.checkedDatas = [];
      }
      this.pId = item.id;

      this.menuData.forEach((itemC, idx) => {
        itemC.isChecked = itemC == item;
      });
      let childNames = this.getChildNames(item);
      this.$emit("returnBack", {
        childIds: this.checkedDatas,
        childNames: childNames,
        parentId: this.pId,
        parentName: item.categoryName
      });
      // let rObj = {
      //   childIds : this.checkedDatas,
      //   parentId : this.pId
      // }
      // this.$emit("returnBack", rObj);
      this.$forceUpdate(); //强刷视图
    }
  },
  watch: {
    // checkedDatas(data){
    //   let rObj = {
    //     childIds : data,
    //     parentId : this.pId
    //   }
    //   this.$emit("returnBack", rObj);
    // },
    checkedDatasParent(oData) {
      if (!oData.parentId) {
        //如果选择全部或者重置
        this.initDataList(); //初始化选中项
        this.checkedDatas = []; //清空二级菜单选中状态
      }
    }
  },
  destroyed() {
    this.countMenuProject = null;
  }
};
</script>
<style lang="less" scoped>
.menu_checks_box {
  position: relative;
  margin: 0 0 5px;
  overflow: hidden;
  &.shrink{
    height: 32px;
    .shrinkBtn{
      position: absolute;
      right: 0;
    }
  }
}
.skeleton_box{
  display: flex;
  margin-bottom: 6px;
  dt {
    font-size: 14px;
    line-height: 32px;
    white-space: nowrap;
    color: #888888;
    margin-right: 20px;
  }
  dd{
    display: flex;
    flex: 1;
    flex-wrap: wrap;
    i{
      display: inline-block;
      width: 80px;
      height: 29px;
      border-radius: 4px;
      background-color: #f5f5f5;
      margin-bottom: 7px;
      margin-right: 8px;
    }
  }
}
.check_dl {
  display: flex;
  dt {
    font-size: 14px;
    line-height: 32px;
    white-space: nowrap;
    color: #888888;
    margin-right: 22px;
  }
  dd {
    display: flex;
    flex-wrap: wrap;
    .check_item {
      cursor: pointer;
      outline: none;
      height: 32px;
      border-radius: 4px;
      font-size: 14px;
      color: #555555;
      line-height: 32px;
      margin-bottom: 7px;
      margin-right: 8px;
      box-sizing: border-box;
      position: relative;
      i {
        display: inline-block;
        line-height: 32px;
        padding: 0 16px;
        font-style: normal;
      }
      &:hover {
        color: #ff924b;
      }
      &.active {
        color: #ff924b;
        background-color: #fff1e8;
      }
    }
  }
}
.shrinkBtn{
  line-height: 32px;
  font-size: 14px;
  font-style: normal;
  color: #ff924b;
  cursor: pointer;
}
.menu_checks_item_box {
  padding: 0 !important;
  width: initial !important;
  transition: all linear 300ms;
  margin-top: 6px !important;
  .is-focus .el-checkbox__inner {
    border-color: #fd7f2c !important;
  }
}
</style>
<style lang="css">
.mypopover {
  padding: 0px;
  margin-top: 5px !important;
}
</style>
